import React, { Component } from 'react';
import {
    Form, Icon, Input, Radio,
    Button, Dropdown, Menu, Table,
    Tag, Pagination, notification,
    Modal, Row, Col, Tabs
} from 'antd';
import axios from '../axios.config';
import JavascriptCommon from '../javascript.common';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, ContentState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';


class Investor extends Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [{
                title: "机构/公司",
                dataIndex: "ZK_TITLE",
                sorter: true
            }, {
                title: "LOGO",
                dataIndex: "ZK_LOGO",
                render: text => <img style={{
                    width: "46px",
                    display: "inherit",
                    margin: "6px 0",
                    borderRadius: "4px"
                }} src={text} alt="暂无图片" />
            }, {
                title: "是否同步",
                dataIndex: "ZK_ISSYNC",
                sorter: true,
                width: 60,
                render: text => { return text === "1" ? <Tag color="blue">已同步</Tag> : <Tag color="orange">未同步</Tag> }
            }, {
                title: "收录时间",
                dataIndex: "EB_CREATE_DATETIME",
                sorter: true,
                render: text => this.formatterDate(text, "-")
            }, {
                title: "最后修改",
                dataIndex: "EB_LASTMODIFY_DATETIME",
                sorter: true,
                render: text => this.formatterDate(text, "-")
            }, {
                title: "操作",
                width: 120,
                render: (text, record, index) => (<Button.Group>
                    <Button type="primary" icon="edit" onClick={() => { this.getRecord(record, index); }} />
                    <Button type="primary" icon="delete" onClick={() => { this.delRecord(record, index); }} />
                </Button.Group>)
            }],
            selection: [],
            records: [],
            tableParam: {
                keyword: "",
                _keyword: "",
                prop: "",
                order: "",
                pagesize: 15,
                pageno: 1,
                total: 0,
                loading: false,
                dropdown: [
                    { key: "ZK_TITLE", value: "机构" },
                    { key: "ZK_ISSYNC", value: "同步" }
                ],
                keycurrent: 0,
                _ZK_DESC: EditorState.createEmpty()
            },
            recordForm: {
                flag: true,
                record: {
                    ZK_INVESTOR: {},
                    ZK_INVESTOR_CASES: [],
                    ZK_INVESTOR_TEAMS: []
                },
                visible: false,
                index: -1
            }
        };
    }
    componentDidMount() {
        this.query();
    }
    query() {
        this.state.tableParam.loading = true;
        this.setState({ tableParam: this.state.tableParam });
        axios.get("Http/Msg/InvestorServer.ashx?method=Backend_GetInvestorList", {
            params: {
                KEYWORD: this.state.tableParam.keyword,
                TYPE: this.state.tableParam.dropdown[this.state.tableParam.keycurrent].key,
                PROP: this.state.tableParam.prop,
                ORDER: this.state.tableParam.order,
                PAGESIZE: this.state.tableParam.pagesize,
                PAGENO: this.state.tableParam.pageno
            }
        }).then(res => {
            this.state.tableParam.loading = false;
            this.setState({ tableParam: this.state.tableParam });
            if (res.data.flag === "True") {
                this.state.tableParam.total = parseInt(res.data.message);
                this.setState({ records: res.data.result });
            }
        });
    }
    currentChange(currentPage) {
        if (this.state.tableParam.pageno !== currentPage) {
            this.state.tableParam.pageno = currentPage;
            this.setState({ tableParam: this.state.tableParam }, () => {
                this.query();
            });
        }
    }
    sortChange(s) {
        if ("field" in s && s.field && s.order) {
            this.state.tableParam.prop = s.field;
            this.state.tableParam.order = s.order + "ing"
            this.state.tableParam.pageno = 1;
            this.query();
        }
    }
    formatterDate(value) {
        return JavascriptCommon.ChangeDateFormat_hhmmss(value, "-");
    }
    updateContent(state) {
        this.state.recordForm._ZK_DESC = state;
        this.state.recordForm.record.ZK_INVESTOR.ZK_DESC = draftToHtml(convertToRaw(state.getCurrentContent()));
        this.setState({ ["recordForm._ZK_DESC"]: state });
    }
    delRecord(record, index) {
        Modal.confirm({
            title: "提示",
            content: "确认删除该记录吗?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/InvestorServer.ashx?method=Backend_DeleteInvestor", { IDS: record.ZK_ID }).then(res => {
                    if (res.data.flag === "True") {
                        this.state.records.splice(index, 1);
                        this.setState({ records: this.state.records }, () => {
                            notification.success({
                                message: "成功",
                                description: "已成功删除记录"
                            });
                        });
                    }
                });
            }
        });
    }
    batchDelete() {
        Modal.confirm({
            title: "提示",
            content: "确认删除所选的记录吗?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/InvestorServer.ashx?method=Backend_DeleteInvestor", { IDS: this.state.selection.join(",") }).then(res => {
                    if (res.data.flag === "True") {
                        notification.success({
                            message: "成功",
                            description: "成功删除多条记录(一秒后将自动刷新页面)"
                        });
                        setTimeout(() => {
                            window.location.reload();
                        }, 1200);
                    }
                });
            }
        });
    }
    getRecord(record, index) {
        axios.get("Http/Msg/InvestorServer.ashx?method=Backend_GetInvestorDetail", { params: { UID: record.ZK_ID } }).then(res => {
            if (res.data.flag === "True") {
                let blocksFromHTML = htmlToDraft(res.data.result.ZK_INVESTOR.ZK_DESC);
                this.state.recordForm._ZK_DESC = EditorState.createWithContent(ContentState.createFromBlockArray(
                    blocksFromHTML.contentBlocks,
                    blocksFromHTML.entityMap
                ));
                this.state.recordForm.record = res.data.result;
                this.state.recordForm.flag = false;
                this.state.recordForm.visible = true;
                this.state.recordForm.index = index;
                this.setState({ recordForm: this.state.recordForm });
            }
        });
    }
    insertRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            for (let key in values) {
                this.state.recordForm.record[key] = values[key];
            }
            //todo
        });
    }
    updateRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            for (let key in values) {
                this.state.recordForm.record.ZK_INVESTOR[key] = values[key];
            }
            axios.post("Http/Msg/InvestorServer.ashx?method=Backend_UpdateInvestor", this.state.recordForm.record.ZK_INVESTOR).then(res => {
                if (res.data.flag === "True") {
                    notification.success({
                        message: "成功",
                        description: "保存记录成功"
                    });
                    this.state.recordForm.visible = false;
                    this.state.records[this.state.recordForm.index] = this.state.recordForm.record.ZK_INVESTOR;
                    this.setState({ recordForm: this.state.recordForm, records: this.state.records });
                }
            });
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div id="investor_temp">
                <div className="toolbar">
                    <Form layout="inline">
                        <Form.Item>
                            <Input
                                placeholder={"请输入关键字（" + this.state.tableParam.dropdown[this.state.tableParam.keycurrent].value + "）"}
                                value={this.state.tableParam._keyword}
                                onChange={e => { this.state.tableParam._keyword = e.target.value; this.setState({ tableParam: this.state.tableParam }); }}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Dropdown overlay={<Menu>
                                {this.state.tableParam.dropdown.map((item, index) => (
                                    <Menu.Item key={item.key} onClick={() => {
                                        this.state.tableParam.pageno = 1;
                                        this.state.tableParam.keycurrent = index;
                                        this.state.tableParam.keyword = this.state.tableParam._keyword;
                                        this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                    }} >
                                        {this.state.tableParam.keycurrent === index ? <b>{item.value}</b> : item.value}
                                    </Menu.Item>
                                ))}
                            </Menu>}>
                                <Button type="primary" onClick={() => {
                                    this.state.tableParam.pageno = 1;
                                    this.state.tableParam.keyword = this.state.tableParam._keyword;
                                    this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                }} >
                                    <Icon type="search" />查询<Icon type="down" />
                                </Button>
                            </Dropdown>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={() => {
                                this.state.recordForm.flag = true;
                                this.state.recordForm.record = {};
                                this.state.recordForm.visible = true;
                                this.state.recordForm._ZK_DESC = EditorState.createEmpty();
                                this.setState({ recordForm: this.state.recordForm });
                            }} disabled>新增</Button>
                        </Form.Item>
                    </Form>
                </div>
                <Table
                    columns={this.state.columns}
                    dataSource={this.state.records}
                    rowKey={record => record.ZK_ID}
                    loading={this.state.tableParam.loading}
                    pagination={false}
                    rowSelection={{ onChange: keys => { this.setState({ selection: keys }); } }}
                    onChange={(p, f, s) => { this.sortChange(s); }}>
                </Table>
                <div className="botton_toolbar">
                    <Button.Group>
                        <Button type="danger" disabled={this.state.selection.length === 0} onClick={() => { this.batchDelete(); }}>
                            <Icon type="delete" />
                            批量删除{this.state.selection.length > 0 ? "(共" + this.state.selection.length + "条)" : ""}
                        </Button>
                        <Button type="primary" disabled={this.state.selection.length === 0 || true} onClick={() => { this.batchDelete(); }}>
                            批量同步{this.state.selection.length > 0 ? "(共" + this.state.selection.length + "条)" : ""}
                            <Icon type="upload" />
                        </Button>
                    </Button.Group>
                    <Pagination
                        size="small"
                        style={{ float: "right" }}
                        total={this.state.tableParam.total}
                        current={this.state.tableParam.pageno}
                        pageSize={this.state.tableParam.pagesize}
                        showQuickJumper
                        showTotal={total => (<span className="recordtotal">共{total}条记录</span>)}
                        onChange={page => { this.currentChange(page); }}
                    />
                </div>
                <Modal
                    title={this.state.recordForm.flag ? "新增" : "编辑"}
                    visible={this.state.recordForm.visible}
                    footer={null}
                    width="80%"
                    maskClosable={false}
                    destroyOnClose={true}
                    onCancel={() => { this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm }); }}
                >
                    <Form onSubmit={e => {
                        if (this.state.recordForm.flag) {
                            this.insertRecord(e)
                        } else {
                            this.updateRecord(e);
                        }
                    }}>
                        <Row gutter={12}>
                            <Col span="12">
                                <Form.Item
                                    label="名　称"
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 20 }}>
                                    {getFieldDecorator("ZK_TITLE", {
                                        initialValue: this.state.recordForm.record.ZK_INVESTOR.ZK_TITLE,
                                        rules: [{ required: true, message: "请输入机构名称" }]
                                    })(<Input />)}
                                </Form.Item>
                            </Col>
                            <Col span="12">
                                <Form.Item
                                    label="LOGO"
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 20 }}>
                                    {getFieldDecorator("ZK_LOGO", {
                                        initialValue: this.state.recordForm.record.ZK_INVESTOR.ZK_LOGO,
                                        rules: [{ required: true, message: "请输入LOGO地址" }]
                                    })(<Input />)}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Form.Item
                            label="简　介"
                            labelCol={{ span: 2 }}
                            wrapperCol={{ span: 22 }}>
                            <Editor
                                localization={{ locale: "zh" }}
                                editorState={this.state.recordForm._ZK_DESC}
                                onEditorStateChange={state => { this.updateContent(state); }}
                            />
                        </Form.Item>
                        <Tabs style={{ marginBottom: "30px" }}>
                            <Tabs.TabPane tab="机构团队" key="teams">
                                <Table
                                    dataSource={this.state.recordForm.record.ZK_INVESTOR_TEAMS}
                                    columns={[{
                                        title: "头像",
                                        dataIndex: "ZK_AVATAR",
                                        render: (text, record) => <img alt={record.ZK_NAME} src={text} width="64" />
                                    }, {
                                        title: "姓名",
                                        dataIndex: "ZK_NAME",
                                        sorter: (a, b) => a - b
                                    }, {
                                        title: "职位",
                                        dataIndex: "ZK_POSITION",
                                        sorter: (a, b) => a - b
                                    }]}
                                    rowKey={record => record.ZK_ID}
                                />
                            </Tabs.TabPane>
                            <Tabs.TabPane tab="投资案例" key="cases">
                                <Table
                                    dataSource={this.state.recordForm.record.ZK_INVESTOR_CASES}
                                    columns={[{
                                        title: "公司/项目",
                                        dataIndex: "ZK_TITLE",
                                        sorter: (a, b) => a - b
                                    }, {
                                        title: "行业",
                                        dataIndex: "ZK_INDUSTRY",
                                        sorter: (a, b) => a - b
                                    }, {
                                        title: "金额",
                                        dataIndex: "ZK_MONEY",
                                        sorter: (a, b) => a - b
                                    }, {
                                        title: "轮次",
                                        dataIndex: "ZK_ROUNDS",
                                        sorter: (a, b) => a - b
                                    }, {
                                        title: "时间",
                                        dataIndex: "ZK_TIME",
                                        sorter: (a, b) => a.ZK_TIME - b.ZK_TIME,
                                        render: text => this.formatterDate(text, "-")
                                    }]}
                                    rowKey={record => record.ZK_ID}
                                />
                            </Tabs.TabPane>
                        </Tabs>
                        <Form.Item>
                            <Row style={{ textAlign: "center" }}>
                                <Col span={8}>
                                    <Button icon="rollback" onClick={() => {
                                        this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm });
                                    }}>
                                        返回
                                    </Button>
                                </Col>
                                <Col span={8}>
                                    <Button type="primary" disabled icon="upload">同步</Button>
                                </Col>
                                <Col span={8}>
                                    <Button type="primary" htmlType="submit" icon="save">保存</Button>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        );
    }
}

Investor = Form.create()(Investor);

export default Investor;